<?php

namespace App\Kuafu\CouponPackage\Model;

use App\Kuafu\Activity\Enum\ActivityEnum;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Base\Model\Traits\KfUid;
use App\Kuafu\Coupon\Model\CouponModel;
use App\Kuafu\CouponPackage\Enum\CouponPackageCodeEnum;
use App\Kuafu\CouponPackage\Enum\CouponPackageEnum;
use App\Kuafu\CouponPackage\Exceptions\CouponPackageException;
use App\Kuafu\Shop\Model\Shop;
use Illuminate\Database\Eloquent\Builder;
use App\Kuafu\Base\Model\BaseModel;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CouponPackageModel extends BaseModel
{
    use KfSoftDeletes, KfUid;

    protected $connection = 'mysql';
    protected $table      = 'coupon_package';
    protected $primaryKey = 'id';
    protected $fillable   = ['name', 'startAt', 'endAt', 'status'];
//    protected $appends    = ['activityTime', 'activityDetailTime'];

    protected $hidden = [
        'updatedAt',
        'isDeleted'
    ];

    public function getTypeTextAttribute(): string
    {
        return ActivityEnum::TYPES[$this->type] ?? '';
    }

    public function getStatusTextAttribute(): string
    {
        return ActivityEnum::STATUS[$this->status] ?? '';
    }

    public function getPopDateAttribute($value)
    {
        return explode(',', $value);
    }

    public function couponPackageMappingRel(): HasMany
    {
        return $this->hasMany(CouponPackageMappingModel::class, 'couponPackageId', 'id');
    }


    public function couponPackageShopMappingRel(): HasMany
    {
        return $this->hasMany(CouponPackageShopMappingModel::class, 'couponPackageId', 'id');
    }

    public function couponPackageMappingInfoRel()
    {
        return $this->hasManyThrough(CouponModel::class, CouponPackageMappingModel::class, 'couponPackageId',
            'id', 'id', 'couponId');
    }

    /**
     * 根据券包id查询券包关联信息
     * @param $id
     * @return Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public static function getCouponPackageInfoById($id)
    {
        return self::query()
                   ->with('couponPackageMappingRel')
                   ->with([
                       'couponPackageShopMappingRel' => function ($query) {
                           $query->select('shopId', 'couponPackageId');
                       }
                   ])
                   ->with('couponPackageMappingInfoRel')
                   ->where('id', '=', $id)
                   ->first();
    }

    /**
     * 减少库存
     * @param int $id
     * @return int
     */
    public static function decrStock(int $id): int
    {
        try {
            return self::query()
                       ->where('id', $id)
                       ->update([
                           'canSaleCount' => DB::raw('canSaleCount-1'),
                       ]);
        } catch (\Exception $e) {

            // 库存不足
            if ($e->getCode() == 22003) {
                Log::info("CouponPackage doBuy stock empty id: {$id}");
                throw new CouponPackageException(CouponPackageCodeEnum::ERR_COUPON_PACKAGE_STOCK_EMPTY);
            }
            throw $e;
        }
    }

    /**
     * 加回库存
     * @param int $id
     * @return int
     */
    public static function reIncrStock(int $id): int
    {
        // 先把『库存为0』的，启用起来
        self::query()->where('id', $id)
            ->where('canSaleCount', 0)
            ->update(['status' => CouponPackageEnum::STATUS_ON]);

        // 库存+1
        return self::query()
                   ->where('id', $id)
                   ->update([
                       'canSaleCount' => DB::raw('canSaleCount+1'),
                   ]);
    }

    /**
     * 新增销售数量
     * @param int $id
     * @return int
     */
    public static function incrSales(int $id): int
    {
        return self::query()->where('id', $id)->update(['hasSaleCount' => DB::raw('hasSaleCount+1')]);
    }

    /**
     * 禁用券
     * @param int $id
     * @return int
     */
    public static function banStatus(int $id)
    {
        return self::query()->where('id', $id)->update(['status' => CouponPackageEnum::STATUS_OFF]);
    }
}
